#include "NetworkHandler.hpp"
#include "Utilities/CollisionHelper.hpp"

NetworkHandler* NetworkHandler::currentInstance = 0;

/**
 * Get access to the NetworkHandler singleton.
 * This method does not instantiate an instance of this class
 * and therefore the NetworkHandler must be instantiated before
 * this method can be called.
 */
NetworkHandler* NetworkHandler::getInstance() {
    return currentInstance;
}

NetworkHandler::NetworkHandler(){
	currentInstance = this;
}

/**
 * Give NetworkHandler access to the ClientCollection.
 * This must be called in order to use this class.
 */
void NetworkHandler::setClientCollection(ClientCollection* cc){
	clientCollection = cc;
}

/** 
* Sends all message except the specified id.
* @param message The message to send.
* @param except Index of client to except.
*/
void NetworkHandler::sendAllMessageExcept(Message::MessageCode code, void* data, int except){
	for(byte i = 0; i < clientCollection->MAX_CLIENTS; i++){
		if(clientCollection->operator[](i)->active && i != except){
			clientCollection->operator[](i)->outQueue.createMessage(code, data);
        }
    }
}

/** 
* Sends all clients the passed message.
* @param message The message to send.
*/
void NetworkHandler::sendAllMessage(Message::MessageCode code, void* data){
	for(byte i = 0; i < clientCollection->MAX_CLIENTS; i++){
		if(clientCollection->operator[](i)->active)
			clientCollection->operator[](i)->outQueue.createMessage(code, data);
    }
}

/**
 * Send all client's whos regions are in x,y.
 * @param code Message Code.
 * @param data Message Data.
 * @param x X location.
 * @param y Y location.
 */
void NetworkHandler::sendAllMessageInArea(Message::MessageCode code, void* data, float x, float y){
    for(byte i = 0; i < clientCollection->MAX_CLIENTS; i++){
        if(clientCollection->operator[](i)->active){
            if(CollisionHelper::collides(clientCollection->operator[](i)->entity.region, x, y)){
                clientCollection->operator[](i)->outQueue.createMessage(code, data);
            }
        }
    }
}

/** 
* Sends all clients a chat message.
* @param message The message to send.
*/
void NetworkHandler::sendAllChatMessage(const char* message){
	Packet_ChatMessage serverMessage = PacketHelper::ChatMessage(message, 255);
	sendAllMessage(Message::m_b_ChatMessage, &serverMessage);
}

NetworkHandler::~NetworkHandler(){
	//Clear pointer values.
	clientCollection = 0;
	currentInstance = 0;
}